import {connect} from 'react-redux'
import React, { Component, ComponentClass } from 'react';
import Taro from '@tarojs/taro';
import {View} from '@tarojs/components'
import {AtSearchBar, AtIndexes} from 'taro-ui'
import {HotCity, CityLocation, AllCity} from '../../utils/server.interface'
import {location} from '../../utils/location.service'
import {setCity, autoLocation} from '../../actions/location'
import {LIAN_GET_LOCATION_LIST} from '../../constants/api'
import {h5Wx} from "../../utils/h5.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import {newHttp} from "../../utils/request";
import {vcmonitor} from "../../utils/tools";
import './select-city.scss'

interface StateType {
  allCity: AllCity[]
  searchKey: string
  searchCity: HotCity[]
}

type PageStateProps = {
  location: CityLocation
}

type PageDispatchProps = {
  setCity: (city: CityLocation) => void
  autoLocation: (city: CityLocation) => void
}

type PageOwnProps = {}

type PageState = {}

type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface SelectCity {
  props: IProps
}

@connect(({location}) => ({
  location
}), (dispatch) => ({
  setCity(city) {
    dispatch(setCity(city))
  },
  autoLocation(city) {
    dispatch(autoLocation(city))
  }
}))

class SelectCity extends Component {
  state: StateType = {
    allCity: [],
    searchKey: '',
    searchCity: []
  }

  async componentDidShow() {
    vcmonitor(this);
  }

  async UNSAFE_componentWillMount() {
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    Taro.showLoading({title: '加载城市中...'})
    const allCity = await newHttp.catchGet(LIAN_GET_LOCATION_LIST, {})
    this.setState({allCity: allCity.group_data})
    Taro.hideLoading()
  }

  async search() {
    const searchCity = await newHttp.catchGet(LIAN_GET_LOCATION_LIST, {city: this.state.searchKey})
    if (searchCity) {
      this.setState({searchCity: searchCity.group_data})
    }
  }

  inputChange(value) {
    this.setState({searchKey: value})
  }

  hotCityHandle(item, e) {
    e.stopPropagation()
    Taro.setStorageSync('lianCity', {area_name:item.items[0].area_name, region_id:item.items[0].region_id})
    this.back()
  }

  indexes(value) {
    const {area_name, region_id} = value
    Taro.setStorageSync('lianCity',{area_name, region_id})
    this.back()
  }

  relocation(e) {
    e.stopPropagation()
    try {
      location.getLocation().then(async (res: any) => {
        if (res == null) {
          console.log('不是微信浏览器');
        } else {
          if (process.env.TARO_ENV === 'h5') {
            const city = await location.getLocationNewH5City(res.longitude, res.latitude, 'wgs84')
            if (city) {
              this.props.autoLocation(city)
            }
          } else {
            const city = await location.getLocationCity(res.longitude, res.latitude)
            if (city) {
              this.props.autoLocation(city)
            }
          }
        }
      });
    } catch (e) {
      Taro.showModal({
        title: '提示',
        content: '您需要开启手机的GPS定位, 才能为您匹配精准的自提点信息'
      })
    }
  }

  back() {
    Taro.navigateBack({
      delta: 1
    })
  }

  clearSearch() {
    this.setState({searchKey: '', searchCity: []})
  }

  render() {
    const {allCity, searchCity, searchKey} = this.state
    return (
      <View className='select-all-city'>
        <GzhAuth />
        <AtIndexes animation onClick={this.indexes.bind(this)} list={allCity}>
          <View className='root'>
            <AtSearchBar value={searchKey} onClear={this.clearSearch.bind(this)} onChange={this.inputChange.bind(this)}
              onActionClick={this.search.bind(this)} placeholder='城市名称，如：北京'
            />
            {searchCity.length > 0 && searchCity.map((item, index) => <View key={index} className='item'
              onClick={this.hotCityHandle.bind(this, item)}
            >{item.items[0].area_name}</View>)}
          </View>
        </AtIndexes>
      </View>
    )
  }
}

export default SelectCity as ComponentClass<PageOwnProps, PageState>
